//
//  GetWeatherData.m
//  BiuWeather
//
//  Created by 楼楚 on 16/2/29.
//  Copyright © 2016年 Chu Lou. All rights reserved.
//

#import "GetWeatherData.h"
#import "weatherView.h"

#define APIkey @"f588ddb737e3a0dd74da9dd50b01787f"
#define HeWeather  @"HeWeather data service 3.0"
#define hourly_forecast @"hourly_forecast"
#define status @"status"
#define daily_forecast @"daily_forecast"
#define aqi @"aqi"
#define basic @"basic"
#define suggestion @"suggestion"
#define now @"now"

@implementation GetWeatherData

-(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg  {
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: APIkey forHTTPHeaderField: @"apikey"];
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error) {
                                   NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
                                   [_delegate sucess:NO];
                               } else {
                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                   NSError *err;
                                   NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
                                   NSArray *arr = [dic objectForKey:HeWeather];
                                   
                                   NSDictionary *dic0 = arr[0];
  
                                   NSDictionary *dic2 = [dic0 objectForKey:daily_forecast];

                                   self.weather = dic0;
                                   
                                   self.weatherData = [[WeatherData alloc]initWithDictionary:self.weather];
                                   [_delegate sucess:YES];
                               }
                           }];
}
- (void)getData
{
    NSString *httpUrl = @"http://apis.baidu.com/heweather/weather/free";
//   NSString *httpArg = @"city=hangzhou";
    NSString *httpArg = self.cityStr;
    [self request: httpUrl withHttpArg: httpArg];
//    NSLog(@"test%@",httpArg);
}

@end
